package com.yunzheng.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzheng.common.BaseResult;
import com.yunzheng.constants.SystemConstants;
import com.yunzheng.entity.ActivityUser;
import com.yunzheng.entity.SysUserProjectRole;
import com.yunzheng.enums.ResultStatuesEnums;
import com.yunzheng.mapper.SysUserProjectRoleMapper;
import com.yunzheng.util.MapperUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 郭思良
 * @create 2020-08-15 20:02
 */

@Slf4j
public class MyPermFilter extends PermissionsAuthorizationFilter {

    public <T> T getBean(Class<T> clazz, HttpServletRequest request){
        WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return applicationContext.getBean(clazz);
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        // TODO: 2020/8/16 先不使用perms过滤器
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        Subject subject = SecurityUtils.getSubject();
        ActivityUser currentUser = (ActivityUser) subject.getPrincipal();
        //进行拦截
        //如果是系统管理员则放行
        String[] perms = (String[]) mappedValue;
        if (currentUser.getUser().getUserIdentify() == 2){
            return true;
        }else{
            SysUserProjectRoleMapper sysUserProjectRoleMapper = getBean(SysUserProjectRoleMapper.class, req);
            // 获取 projectId，查询数据库获得roleId
            String projectId = req.getHeader(SystemConstants.PROJECT_ID);
            String roleId = sysUserProjectRoleMapper.selectOne(new QueryWrapper<SysUserProjectRole>().eq(SysUserProjectRole.COL_USER_ID, currentUser.getUser().getUserId())
                    .eq(SysUserProjectRole.COL_PROJECT_ID, projectId)).getRoleId();
            //如果是普通用户则核对角色信息
            for (String role : perms){
                if (role.equals(roleId)){
                    return true;
                }
            }
        }
        // 设置响应头部信息
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json");
        // 设置返回message
        StringBuilder message = new StringBuilder();
        StringUtils.join(perms,',', message);
        //返回消息
        ResultStatuesEnums badRole = ResultStatuesEnums.BAD_ROLE;
        badRole.setMessage("您没有该[" + message + "]角色");
        res.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(badRole)));

        return false;
    }
}
